package com.deep.ware.service.impl;

import com.deep.common.model.dto.OrderDTO;
import com.deep.common.model.dto.SkuHasStockTO;
import com.deep.common.model.dto.mq.StockDetailDTO;
import com.deep.common.model.dto.mq.StockLockedDTO;
import com.deep.common.utils.R;
import com.deep.ware.exception.NoStockException;
import com.deep.ware.model.dto.WareSkuLockDTO;
import com.deep.ware.model.entity.WareOrderTaskDetailEntity;
import com.deep.ware.model.entity.WareOrderTaskEntity;
import com.deep.ware.model.vo.OrderItemVO;
import com.deep.ware.model.vo.WareSkuEntityVO;
import com.deep.ware.feign.ProductFeignService;
import com.deep.ware.service.WareOrderTaskDetailService;
import com.deep.ware.service.WareOrderTaskService;
import lombok.Data;
import org.apache.shiro.util.Assert;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deep.common.utils.PageUtils;
import com.deep.common.utils.Query;

import com.deep.ware.dao.WareSkuDao;
import com.deep.ware.model.entity.WareSkuEntity;
import com.deep.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryDetail(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        String wareId = (String) params.get("wareId");
        if (StringUtils.hasLength(wareId)) {
            wrapper.eq("ware_id", wareId);
        }
        String skuId = (String) params.get("skuId");
        if (StringUtils.hasLength(skuId)) {
            wrapper.eq("sku_id", skuId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void saveDetail(WareSkuEntityVO wareSkuVO) {
        Assert.notNull(wareSkuVO, "wareSkuVO不能为空!");
        WareSkuEntity wareSkuEntity = new WareSkuEntity();
        BeanUtils.copyProperties(wareSkuVO, wareSkuEntity);
        this.save(wareSkuEntity);
    }

    @Transactional
    @Override
    public BigDecimal addStock(Long skuId, Long wareId, Integer skuNum) {

        // 1、查询数据库是否有该商品
        WareSkuEntity wareSkuEntity = this.getBaseMapper()
                .selectOne(
                        new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId)
                                .eq("ware_id", wareId)
                );
        BigDecimal price = new BigDecimal(0);
        if (wareSkuEntity == null) {
            // 没有则库存新增
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setWareId(wareId);
            skuEntity.setStock(skuNum);
            skuEntity.setStockLocked(0);
            // 2、新增商品
            this.getBaseMapper().insert(skuEntity);
        } else {
            wareSkuEntity.setStock(wareSkuEntity.getStock() + skuNum);
            this.updateById(wareSkuEntity);
        }
        // TODO 还可以用什么办法让异常出现以后不回滚？高级
        // 3、远程调用product模块获取商品名和价格
        try {
            R info = productFeignService.info(skuId);
            Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
            // 获取sku成功
            if (info.getCode() == 0) {
                wareSkuEntity.setSkuName((String) data.get("skuName"));
                // 获取单件商品价格
                price = BigDecimal.valueOf((Double) data.get("price"));
            }
        } catch (Exception e) {
            System.out.println("com.deep.mall.ware.service.impl.WareSkuServiceImpl：远程调用出错");
        }

        // 4、返回商品单价
        return price;
    }

    @Override
    public List<SkuHasStockTO> getSkusHasStock(List<Long> skuIds) {
        return skuIds.stream().map(skuId -> {
            SkuHasStockTO stockTO = new SkuHasStockTO();
            // 1、不止一个仓库有，多个仓库都有库存 sum
            // 2、锁定库存是别人下单但是还没下完
            Long count = baseMapper.getSkuStock(skuId);
            stockTO.setSkuId(skuId);
            stockTO.setHasStock(count != null && count > 0);
            return stockTO;
        }).collect(Collectors.toList());
    }

    /**
     * 锁定库存
     *
     * @Transactional默认运行时异常都会回滚
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean lockStock(WareSkuLockDTO lockDTO) {
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(lockDTO.getOrderSn());
        wareOrderTaskEntity.setCreateTime(new Date());
        // 保存工作单（不一定锁库存成功）
        wareOrderTaskService.save(wareOrderTaskEntity);
        // 1、按照下单的收货地址，找到一个就近仓库，锁定库存
        // 2、找到每个商品在哪个仓库都有库存
        List<OrderItemVO> locks = lockDTO.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map((item) -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            // 查询这个商品在哪个仓库有库存 stock-锁定num > 0
            List<Long> wareIdList = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIdList);

            return stock;
        }).collect(Collectors.toList());

        // 3、锁定库存
        for (SkuWareHasStock hasStock : collect) {
            boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();

            if (CollectionUtils.isEmpty(wareIds)) {
                //没有任何仓库有这个商品的库存
                throw new NoStockException("没有该库存,skuId:" + skuId);
            }
            // 3.1、如果每一个商品都锁定成功,将当前商品锁定了几件的工作单记录发给MQ
            // 3.2、锁定失败。前面保存的工作单信息都回滚了。发送出去的消息，即使要解锁库存，由于在数据库查不到指定的id，所有就不用解锁
            for (Long wareId : wareIds) {
                // 锁定成功就返回1，失败就返回0
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                // count==1表示锁定成功
                if (count == 1) {
                    skuStocked = true;
                    // 保存工作单详情（便于订单取消回溯）
                    WareOrderTaskDetailEntity taskDetailEntity = WareOrderTaskDetailEntity.builder()
                            .skuId(skuId)
                            .skuName("")
                            .skuNum(hasStock.getNum())
                            .taskId(wareOrderTaskEntity.getId())
                            .wareId(wareId)
                            .lockStatus(1)
                            .build();
                    wareOrderTaskDetailService.save(taskDetailEntity);
                    //TODO 告诉MQ库存锁定成功
                    StockLockedDTO lockedDTO = new StockLockedDTO();
                    lockedDTO.setId(wareOrderTaskEntity.getId());

                    StockDetailDTO detailDTO = new StockDetailDTO();
                    BeanUtils.copyProperties(taskDetailEntity, detailDTO);// 这里直接存entity。但是应该存id更好，数据最好来自DB
                    lockedDTO.setDetailTo(detailDTO);

                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", lockedDTO);
                    // 锁定成功返回
                    break;
                } else {
                    //当前仓库锁失败，重试下一个仓库
                }
            }
            if (!skuStocked) {
                // 当前商品所有仓库都没有锁住
                throw new NoStockException("锁定库存失败,skuId:" + skuId);
            }
        }
        // 库存全部锁定成功
        return true;
    }

    @Override
    public int unLockStock(Long skuId, Long wareId, Integer num) {
        return wareSkuDao.unLockStock(skuId, wareId, num);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int unlockStock(OrderDTO orderDTO) {
        String orderSn = orderDTO.getOrderSn();
        WareOrderTaskEntity taskEntity = wareOrderTaskService
                .getOne(new QueryWrapper<WareOrderTaskEntity>().eq("order_sn", orderSn));
        List<WareOrderTaskDetailEntity> detailEntityList = wareOrderTaskDetailService.getBaseMapper()
                .selectList(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", taskEntity.getId()));
        for (WareOrderTaskDetailEntity detailEntity : detailEntityList) {
            unLockStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum());
        }
        return 0;
    }

    @Data
    static class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }
}